#include <iostream>
#include <fstream>
#include <string>
#include "contacts.pb.h"

void AddContact(contacts::PeopleInfo *con)
{
    std::cout<<"---------------新增联系人---------------"<<std::endl;
    std::cout<<"输入联系人姓名: ";
    std::string name;
    std::getline(std::cin, name);
    con->set_name(name);
    int age = 0;
    std::cout<<"输入联系人年龄: ";
    std::cin >> age;
    con->set_age(age);
    // 清空cin缓冲区
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    // 新增电话
    for(int i = 1;true;i++)
    {
        std::cout<<"---请输入该联系人的电话"<<i<<"(只输入空格表示完成)"<<": ";
        std::string number;
        std::getline(std::cin,number);
        if(number.size() == 0) break;
        contacts::PeopleInfo_Phone* phone = con->add_phones();
        phone->set_phone(number);
    }
     std::cout<<"---------------添加联系人成功---------------"<<std::endl;
}
int main()
{
    contacts::Contacts cons;
    std::ifstream in("contacts.bin", std::ios::binary);
    if (!in.is_open())
    {
        std::cout << "contacts.bin is not exist,create new contacts.bin" << std::endl;
    }
    else if (!cons.ParseFromIstream(&in))
    {
        std::cout << "Parse contact info error!" << std::endl;
        in.close();
        return -1;
    }

    AddContact(cons.add_contacts());

    // 序列化写入文件
    std::ofstream out("contacts.bin", std::ios::trunc | std::ios::binary);
    if (!out.is_open())
    {
        std::cout << "write file error!" << std::endl;
        return -2;
    }
    if (!cons.SerializePartialToOstream(&out))
    {
        std::cout << "序列化失败!" << std::endl;
        return -3;
    }
    
    in.close();
    out.close();
    return 0;
}